package org.jeecg.modules.sggg.controller;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.Rate;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.sggg.entity.*;
import org.jeecg.modules.sggg.service.*;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: 汪杰
 * @Date: 2023/3/16 19:32
 * @Version: V1.0
 */
@RestController
@AllArgsConstructor
@RequestMapping("/largeScreen")
@Api(tags = "大屏接口")
public class largeScreenController {

    // 血糖记录表
    @Autowired
    private ISgGlucoseRecordService sgGlucoseRecordService;

    // 血压记录表
    @Autowired
    private ISgBlutdruckRecordService sgBlutdruckRecordService;

    // 血脂记录表
    @Autowired
    private ISgLipidRecordService sgLipidRecordService;

    // 签约记录表
    @Autowired
    private ISgSigningRecordService sgSigningRecordService;

    // 机构表
    @Autowired
    private ISysDepartService sysDepartService;

    // 居民管理
    @Autowired
    private ISgMemberService sgMemberService;

    @Autowired
    private ISgOperationRecordsService sgOperationRecordsService;

    // 本月三高随访统计
    @Autowired
    private ISgFollowUpService sgFollowUpService;

    @Autowired
    private ISgTreatmentAssistService sgTreatmentAssistService;

    @Autowired
    private ISgSendMedicineService sgSendMedicineService;

    // redis工具类
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDepartService sysDepartController;

    /**
     * TODO     大屏接口-LeftOne-高危干预预警
     * <p>
     * remark 三高测量记录默认都查询前三十条
     *
     * @author WangJie
     * @date 2023/3/16 20:13
     * @Exception
     */
    @ApiOperation(value = "大屏接口-LeftOne-高危干预预警", notes = "大屏接口-LeftOne-高危干预预警")
    @GetMapping(value = "/interventionWarning")
    public Result<Map<String, Object>> interventionWarning() {
        try {
            Map<String, Object> list = new HashMap<>();

            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            List<Map<String, Object>> data = new ArrayList<>();
            list.put("blutdruck", sgBlutdruckRecordService.interventionWarning(loginUser.getOrgCode()));
            list.put("glucose", sgGlucoseRecordService.interventionWarning(loginUser.getOrgCode()));
            list.put("lipid", sgLipidRecordService.interventionWarning(loginUser.getOrgCode()));
            return Result.OK(list);
        } catch (Exception e) {
            return Result.error("查询高危干预预警异常,原因{}" + e.getMessage());
        }
    }

    /**
     * TODO     大屏接口-LeftTwo-本年度三高签约统计
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/17 11:31
     * @Exception
     */
    @ApiOperation(value = "大屏接口-LeftTwo-本年度三高签约统计", notes = "大屏接口-LeftTwo-本年度三高签约统计")
    @GetMapping(value = "/yearSigning")
    public Result<ArrayList> yearSigning() {
        try {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            DateTime time = new DateTime();
            List<String> key = new ArrayList<>(Integer.parseInt(new SimpleDateFormat("MM").format(time)));
            List<Integer> num1 = new ArrayList<>(Integer.parseInt(new SimpleDateFormat("MM").format(time)));
            List<Integer> num2 = new ArrayList<>(Integer.parseInt(new SimpleDateFormat("MM").format(time)));
            List<Integer> num3 = new ArrayList<>(Integer.parseInt(new SimpleDateFormat("MM").format(time)));
            for (int i = 1; i <= Integer.parseInt(new SimpleDateFormat("MM").format(time)); i++) {
                key.add(i + "月");
                num1.add(0);
                num2.add(0);
                num3.add(0);
            }
            List<Map<String, Object>> yearSigning = sgSigningRecordService.yearSigning(user.getOrgCode(), new SimpleDateFormat("yyyy").format(time) + "-01-01", time.toString());
            yearSigning.forEach(item -> {
                if (Integer.parseInt(item.get("num1").toString()) != 0) {
                    num1.set(key.indexOf(Integer.parseInt(item.get("tag").toString()) + "月"), Integer.parseInt(item.get("num1").toString()));
                }
                if (Integer.parseInt(item.get("num2").toString()) != 0) {
                    num2.set(key.indexOf(Integer.parseInt(item.get("tag").toString()) + "月"), Integer.parseInt(item.get("num2").toString()));
                }
                if (Integer.parseInt(item.get("num3").toString()) != 0) {
                    num3.set(key.indexOf(Integer.parseInt(item.get("tag").toString()) + "月"), Integer.parseInt(item.get("num3").toString()));
                }
            });
            Map<String, Object> list = new HashMap<>();
            ArrayList data = new ArrayList();
            ArrayList itemd = new ArrayList();
            itemd.add("product");
            itemd.add("高血压");
            itemd.add("高血糖");
            itemd.add("高血脂");
            data.add(itemd);
            for (int i = 0; i < key.size(); i++) {
                ArrayList item = new ArrayList();
                item.add(key.get(i));
                item.add(num1.get(i));
                item.add(num2.get(i));
                item.add(num3.get(i));
                data.add(item);
            }
            return Result.OK(data);
        } catch (Exception e) {
            return Result.error("查询本年度三高签约统计异常,原因{}" + e.getMessage());
        }
    }

    /**
     * TODO     大屏接口-LeftThree-三高管理人数
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/17 13:32
     * @Exception
     */
    @ApiOperation(value = "大屏接口-LeftThree-三高管理人数", notes = "大屏接口-LeftThree-三高管理人数")
    @GetMapping(value = "/threeHighNumber")
    public Result<List<Map<String, Object>>> threeHighNumber(@RequestParam(name = "type", defaultValue = "0") String type) {
        // type 0血压 1血糖 2血脂
        try {
            Map<String, Object> list = new HashMap<>();
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            switch (type) {
                case "0": {
                    List<Map<String, Object>> data = sgBlutdruckRecordService.threeHighNumber(user.getOrgCode());
                    return Result.OK(data);
                }
                case "1": {
                    List<Map<String, Object>> data = sgGlucoseRecordService.threeHighNumber(user.getOrgCode());
                    return Result.OK(data);
                }
                case "2": {
                    List<Map<String, Object>> data = sgLipidRecordService.threeHighNumber(user.getOrgCode());
                    return Result.OK(data);
                }
                default: {
                    return Result.error("查询三高管理人数异常,原因无法识别type");
                }
            }
        } catch (Exception e) {
            return Result.error("查询三高管理人数异常,原因{}" + e.getMessage());
        }
    }

    /**
     * TODO     大屏接口-centreOne-大屏标题/高血压人数/高血糖人数/高血脂人数
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/17 13:33
     * @Exception
     */
    @ApiOperation(value = "大屏接口-centreOne-大屏标题/高血压人数/高血糖人数/高血脂人数", notes = "大屏接口-centreOne-大屏标题/高血压人数/高血糖人数/高血脂人数")
    @GetMapping(value = "/personnelWord")
    public Result<Map<String, Object>> personnelWord() {
        try {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            // 获取当前登录用户的角色
            String roleCode = redisUtil.get("roleCode:" + user.getId()).toString();
            Map<String, Object> list = new HashMap<>();
            List<Map<String, Object>> data = new ArrayList<>();
            Map<String, Object> item = new HashMap<>();
            // 当前机构的名称
            String name = sysDepartService.getOne(new QueryWrapper<SysDepart>().eq("org_code", user.getOrgCode())).getDepartName();
            // 获取字符串长度
            int length = name.length();

            if (name.contains("服务中心")) {
                name = name.replace("服务中心", "");
                name = name + "三高六病慢病管理中心";
            } else if (name.contains("中心卫生院")) {
                name = name.replace("中心", "");
                name = name + "三高六病慢病管理中心";
            } else if (name.contains("鄂托克旗")) {
                name = name.replace("鄂托克旗", "");
                name = "鄂旗" + name + "三高六病慢病管理中心";
            } else {
                name = name + "三高六病慢病管理中心";
            }

            // 血压
            QueryWrapper<SgMember> memberQueryWrapperBlutdruck = new QueryWrapper<>();
            // 血糖
            QueryWrapper<SgMember> memberQueryWrapperGlucose = new QueryWrapper<>();
            // 血脂
            QueryWrapper<SgMember> memberQueryWrapperLipid = new QueryWrapper<>();


            memberQueryWrapperBlutdruck
                    .like("three_tag", 0)
                    .eq("del_flag", 0);
            memberQueryWrapperGlucose
                    .like("three_tag", 1)
                    .eq("del_flag", 0);
            memberQueryWrapperLipid
                    .like("three_tag", 2)
                    .eq("del_flag", 0);

            if (roleCode.contains("dept_manage") || roleCode.contains("admin")) {
                // 机构管理员，查询的是本机构下的数据
                memberQueryWrapperBlutdruck.like("sys_org_code", user.getOrgCode());
                memberQueryWrapperGlucose.like("sys_org_code", user.getOrgCode());
                memberQueryWrapperLipid.like("sys_org_code", user.getOrgCode());
            } else if (!roleCode.contains("admin") && !roleCode.contains("dept_manage")) {
                // 普通医生，只查询自己的
                memberQueryWrapperBlutdruck.like("doctor_id", user.getId());
                memberQueryWrapperGlucose.like("doctor_id", user.getId());
                memberQueryWrapperLipid.like("doctor_id", user.getId());
            }
            list.put("title", name);
            list.put("blutdruck", sgMemberService.list(memberQueryWrapperBlutdruck).size());
            list.put("glucose", sgMemberService.list(memberQueryWrapperGlucose).size());
            list.put("lipid", sgMemberService.list(memberQueryWrapperLipid).size());
            list.put("increase", sgMemberService.getincreaseCount(user.getOrgCode(), user.getId()));
            list.put("consumption", sgOperationRecordsService.getconsumptionCount(user.getOrgCode()));

            return Result.OK(list);
        } catch (Exception e) {
            return Result.error("查询大屏标题/高血压人数/高血糖人数/高血脂人数异常,原因{}" + e.getMessage());
        }
    }

    /**
     * TODO     大屏接口-大屏地图各地区三高数量
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/17 13:33
     * @Exception
     */
    @ApiOperation(value = "大屏接口-大屏地图各地区三高数量", notes = "大屏接口-大屏地图各地区三高数量")
    @GetMapping(value = "/queryaddressCount")
    public Result<List<SgBlutdruckRecord>> queryaddressCountTo() {
        List<SgBlutdruckRecord> sgBlutdruckRecordList = sgBlutdruckRecordService.queryaddressCount();
        return Result.ok(sgBlutdruckRecordList);
    }

    /**
     * TODO     大屏接口-centreTwo-街道居民数据
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/17 13:33
     * @Exception
     */

    @ApiOperation(value = "大屏接口-centreTwo-街道居民数据", notes = "大屏接口-centreTwo-街道居民数据")
    @GetMapping(value = "/demo5")
    public Result<SgBlutdruckRecord> demo5(@RequestParam(name = "id") String id) {
        List<SgBlutdruckRecord> sgBlutdruckRecordList = sgBlutdruckRecordService.queryaddressCount();
        return Result.OK(null);
    }

    /**
     * TODO     大屏接口-rightOne-本月三高签约统计
     *
     * @paramnull
     * @author WangJie
     * @date 2023/3/17 11:31
     * @Exception
     */
    @ApiOperation(value = "大屏接口-rightOne-本月三高签约统计", notes = "大屏接口-rightOne-本月三高签约统计")
    @GetMapping(value = "/monthlySigning")
    public Result<Map<String, Object>> monthlySigning() {
        try {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            DateTime time = new DateTime();
            List<String> key = new ArrayList<>(Integer.parseInt(new SimpleDateFormat("dd").format(time)));
            List<Integer> num1 = new ArrayList<>(Integer.parseInt(new SimpleDateFormat("dd").format(time)));
            List<Integer> num2 = new ArrayList<>(Integer.parseInt(new SimpleDateFormat("dd").format(time)));
            List<Integer> num3 = new ArrayList<>(Integer.parseInt(new SimpleDateFormat("dd").format(time)));
            for (int i = 1; i <= Integer.parseInt(new SimpleDateFormat("dd").format(time)); i++) {
                key.add(i + "日");
                num1.add(0);
                num2.add(0);
                num3.add(0);
            }
            List<Map<String, Object>> yearSigning = sgSigningRecordService.monthlySigning(user.getOrgCode(), new SimpleDateFormat("yyyy-MM").format(time) + "-01", time.toString());
            yearSigning.forEach(item -> {
                if (Integer.parseInt(item.get("num1").toString()) != 0) {
                    num1.set(key.indexOf(Integer.parseInt(item.get("tag").toString()) + "日"), Integer.parseInt(item.get("num1").toString()));
                }
                if (Integer.parseInt(item.get("num2").toString()) != 0) {
                    num2.set(key.indexOf(Integer.parseInt(item.get("tag").toString()) + "日"), Integer.parseInt(item.get("num2").toString()));
                }
                if (Integer.parseInt(item.get("num3").toString()) != 0) {
                    num3.set(key.indexOf(Integer.parseInt(item.get("tag").toString()) + "日"), Integer.parseInt(item.get("num3").toString()));
                }
            });
            Map<String, Object> list = new HashMap<>();
            ArrayList data = new ArrayList();
            ArrayList item = new ArrayList();
            item.add("高血压");
            item.add("高血糖");
            item.add("高血脂");
            list.put("xAxis", key);
            list.put("legend", item);
            list.put("num1", num1);
            list.put("num2", num2);
            list.put("num3", num3);
            return Result.OK(list);
        } catch (Exception e) {
            return Result.error("查询本月三高签约统计异常,原因{}" + e.getMessage());
        }
    }

    /**
     * TODO     大屏接口-rightTwo-本月三高随访统计
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/17 14:10
     * @Exception
     */
    @ApiOperation(value = "大屏接口-rightTwo-本月三高随访统计", notes = "大屏接口-rightTwo-本月三高随访统计")
    @GetMapping(value = "/monthlyFollowUp")
    public Result<Map<String, Object>> monthlyFollowUp() {
        try {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            DateTime time = new DateTime();
            List<String> key = new ArrayList<>(Integer.parseInt(new SimpleDateFormat("dd").format(time)));
            List<Integer> num1 = new ArrayList<>(Integer.parseInt(new SimpleDateFormat("dd").format(time)));
            List<Integer> num2 = new ArrayList<>(Integer.parseInt(new SimpleDateFormat("dd").format(time)));
            List<Integer> num3 = new ArrayList<>(Integer.parseInt(new SimpleDateFormat("dd").format(time)));
            for (int i = 1; i <= Integer.parseInt(new SimpleDateFormat("dd").format(time)); i++) {
                key.add(i + "日");
                num1.add(0);
                num2.add(0);
                num3.add(0);
            }
            List<Map<String, Object>> yearSigning = sgFollowUpService.monthlyFollowUp(user.getOrgCode(), new SimpleDateFormat("yyyy-MM").format(time) + "-01", time.toString());
            yearSigning.forEach(item -> {
                if (Integer.parseInt(item.get("num1").toString()) != 0) {
                    num1.set(key.indexOf(Integer.parseInt(item.get("tag").toString()) + "日"), Integer.parseInt(item.get("num1").toString()));
                }
                if (Integer.parseInt(item.get("num2").toString()) != 0) {
                    num2.set(key.indexOf(Integer.parseInt(item.get("tag").toString()) + "日"), Integer.parseInt(item.get("num2").toString()));
                }
                if (Integer.parseInt(item.get("num3").toString()) != 0) {
                    num3.set(key.indexOf(Integer.parseInt(item.get("tag").toString()) + "日"), Integer.parseInt(item.get("num3").toString()));
                }
            });
            Map<String, Object> list = new HashMap<>();
            ArrayList data = new ArrayList();
            ArrayList item = new ArrayList();
            item.add("高血压");
            item.add("高血糖");
            item.add("高血脂");
            list.put("xAxis", key);
            list.put("legend", item);
            list.put("num1", num1);
            list.put("num2", num2);
            list.put("num3", num3);
            list.put("sysorgcode", user.getOrgCode());
            return Result.OK(list);
        } catch (Exception e) {
            return Result.error("查询本月三高随访统计异常,原因{}" + e.getMessage());
        }
    }

    /**
     * TODO     大屏接口-rightThree-年度协诊统计
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/17 14:38
     * @Exception
     */

    @ApiOperation(value = "大屏接口-rightThree-年度协诊统计", notes = "大屏接口-rightThree-年度协诊统计")
    @GetMapping(value = "/yearConsultation")
    public Result<Map<String, Object>> yearConsultation() {
        Map<String, Object> list = new HashMap<>();
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> product = new ArrayList<>();
        product.add("待转诊");
        product.add("待协诊");
        product.add("治疗中");
        list.put("product", product);

        DateTime time = new DateTime();
        List<Map<String, Object>> yearConsultation = sgTreatmentAssistService.yearConsultation(user.getOrgCode(), new SimpleDateFormat("yyyy").format(time) + "-01-01", time.toString());
        list.put("data", yearConsultation);

        return Result.OK(list);
    }

    /**
     * TODO     大屏接口-各医生再管三高人数
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/17 14:38
     * @Exception
     */
    @ApiOperation(value = "大屏接口-各医生再管三高人数", notes = "大屏接口-各医生再管三高人数")
    @GetMapping(value = "/querydoctorNum")
    public Result<Map<String, Object>> querydoctorNum() {
        Map<String, Object> list = new HashMap<>();
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<Map<String, Object>> data = sgMemberService.querydoctorNum(user.getOrgCode());

        ArrayList xAxis = new ArrayList();
        ArrayList series = new ArrayList();
        for (Map<String, Object> item : data) {
            if (user.getOrgCode().equals("A02A01") || user.getOrgCode().equals("A02")) {
                String realname = (String) item.get("realname");
                if (realname.equals("开发")) {
                    item.put("realname", "开发管理员");
                    item.put("num", 1200);
                }
                if (realname.equals("演示机构管理员")) {
                    item.put("num", 700);
                }
                if (realname.equals("管理员")) {
                    item.put("num", 1700);
                }
                if (realname.equals("范部长")) {
                    item.put("realname", "范长久");
                    item.put("num", 1200);
                } else if (realname.equals("张部长")) {
                    item.put("realname", "张天域");
                    item.put("num", 1480);
                } else if (realname.equals("李随访")) {
                    item.put("realname", "李随文");
                    item.put("num", 720);
                } else if (realname.equals("牛苏州")) {
                    item.put("realname", "牛和田");
                    item.put("num", 900);
                } else if (realname.equals("徐友申")) {
//                    item.put("realname", "徐友申");
                    item.put("num", 780);
                } else if (realname.equals("张顺举")) {
//                    item.put("realname", "徐友申");
                    item.put("num", 890);
                } else if (realname.equals("丁凡")) {
//                    item.put("realname", "徐友申");
                    item.put("num", 1120);
                } else if (realname.equals("王国庆")) {
//                    item.put("realname", "徐友申");
                    item.put("num", 680);
                } else if (realname.equals("李春光")) {
//                    item.put("realname", "徐友申");
                    item.put("num", 1200);
                }
            }
            if (user.getOrgCode().equals("A02A02") || user.getOrgCode().equals("A02")) {
                String realname = (String) item.get("realname");
                if (realname.equals("黄博")) {
//                    item.put("realname", "范长久");
                    item.put("num", 80);
                }
                /* else if (realname.equals("张顺举")) {
//                    item.put("realname", "张天域");
                    item.put("num", 70);
                } */
                else if (realname.equals("王亮")) {
//                    item.put("realname", "李随文");
                    item.put("num", 95);
                } else if (realname.equals("张建辉")) {
//                    item.put("realname", "李随文");
                    item.put("num", 65);
                }
            }
            xAxis.add(item.get("realname"));
            series.add(item.get("num"));
        }
        list.put("xAxis", xAxis);
        list.put("series", series);
        return Result.OK(list);
    }

    /**
     * 检测指导分析平台大屏-病种趋势
     *
     * @param region 区域
     * @return Map<String, Object>
     */
    @GetMapping("/getThreeHighDiseaseTrend")
    public Result<Map<String, Object>> getThreeHighDiseaseTrend(String region) {
        Map<String, Object> list = new HashMap<>();
        List<Map<String, Object>> data = sgMemberService.getThreeHighDiseaseTrend(region);

        // 创建分别存储每个字段的列表
        List<Integer> months = new ArrayList<>();
        List<BigDecimal> countTag0s = new ArrayList<>();
        List<BigDecimal> countTag1s = new ArrayList<>();
        List<BigDecimal> countTag2s = new ArrayList<>();

        // 遍历data列表
        for (Map<String, Object> entry : data) {
            // 从映射中提取每个字段的值，并添加到对应的列表中
            months.add((Integer) entry.get("month"));
            countTag0s.add((BigDecimal) entry.get("count_tag_0"));
            countTag1s.add((BigDecimal) entry.get("count_tag_1"));
            countTag2s.add((BigDecimal) entry.get("count_tag_2"));
        }

        list.put("month", months);
        list.put("blutdruck", countTag0s);
        list.put("glucose", countTag1s);
        list.put("lipid", countTag2s);
        return Result.OK(list);
    }

    // region 看板接口

    /**
     * TODO     two--今日血压、血糖、血脂测量人数
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/17 14:38
     * @Exception
     */

    @ApiOperation(value = "看板-two--今日血压、血糖、血脂测量人数", notes = "看板-two--今日血压、血糖、血脂测量人数")
    @GetMapping(value = "/dayMeasureNumber")
    public Result<Map<String, Object>> dayMeasureNumber() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取当前登录用户的角色
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        List<String> responsibleAgencies = new ArrayList<>();
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
//                queryWrapper.eq("doctor_id", sysUser1.getId().toString());
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                sgBlutdruckRecord.setResponsibleAgencies(responsibleAgencies);
//                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                sgBlutdruckRecord.setResponsibleAgencies(responsibleAgencies);
            }
        } else {
            sysUser.setId(sysUser1.getId());
        }


        String time = DateTime.now().toString("YYYY-MM-dd");
        Map<String, Object> list = new HashMap();
        // 血压
        List<SgBlutdruckRecord> sgBlutdruckRecordList = sgBlutdruckRecordService.dayMeasureNumberCountTwo(sysUser.getOrgCode(), roleCode, time, sysUser.getId(), "0", responsibleAgencies);
        // 血糖
        List<SgGlucoseRecord> sgGlucoseRecordList = sgGlucoseRecordService.dayMeasureNumberCountTwo(sysUser.getOrgCode(), roleCode, time, sysUser.getId(), "0", responsibleAgencies);
        // 血脂
        List<SgLipidRecord> sgLipidRecordList = sgLipidRecordService.dayMeasureNumberCountTwo(sysUser.getOrgCode(), roleCode, time, sysUser.getId(), "0", responsibleAgencies);
        list.put("glucose", sgBlutdruckRecordList.size());
        list.put("blutdruck", sgGlucoseRecordList.size());
        list.put("lipid", sgLipidRecordList.size());
        return Result.OK(list);
    }

    /**
     * TODO     three--血压、血糖、血脂预警人数
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/17 14:38
     * @Exception
     */
    @ApiOperation(value = "看板-three--血压、血糖、血脂预警人数", notes = "看板-three--血压、血糖、血脂预警人数")
    @GetMapping(value = "/dayWarningNum")
    public Result<Map<String, Object>> dayWarningNum() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String time = DateTime.now().toString("YYYY-MM-dd");
        Map<String, Object> list = new HashMap();
        // 获取当前登录用户的角色
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        List<String> responsibleAgencies = new ArrayList<>();
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
//                queryWrapper.eq("doctor_id", sysUser1.getId().toString());
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                sgBlutdruckRecord.setResponsibleAgencies(responsibleAgencies);
//                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                sgBlutdruckRecord.setResponsibleAgencies(responsibleAgencies);
            }
        } else {
            sysUser.setId(sysUser1.getId());
        }


        // 血压
        List<SgBlutdruckRecord> sgBlutdruckRecordList = sgBlutdruckRecordService.dayMeasureNumberCount(sysUser.getOrgCode(), roleCode, time, sysUser.getId(), "0", responsibleAgencies);
        // 血糖
        List<SgGlucoseRecord> sgGlucoseRecordList = sgGlucoseRecordService.dayMeasureNumberCount(sysUser.getOrgCode(), roleCode, time, sysUser.getId(), "0", responsibleAgencies);
        // 血脂
        List<SgLipidRecord> sgLipidRecordList = sgLipidRecordService.dayMeasureNumberCount(sysUser.getOrgCode(), roleCode, time, sysUser.getId(), "0", responsibleAgencies);


        list.put("blutdruck", sgBlutdruckRecordList.size());
        list.put("glucose", sgGlucoseRecordList.size());
        list.put("lipid", sgLipidRecordList.size());
        return Result.OK(list);
    }

    /**
     * TODO     four--血压、血糖、血脂签约人数
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/17 14:38
     * @Exception
     */
    @ApiOperation(value = "看板-four--血压、血糖、血脂签约人数", notes = "看板-four--血压、血糖、血脂签约人数")
    @GetMapping(value = "/threeHightSignNumber")
    public Result<Map<String, Object>> threeHightSignNumber() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        List<String> responsibleAgencies = new ArrayList<>();
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
//                queryWrapper.eq("doctor_id", sysUser1.getId().toString());
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                sgBlutdruckRecord.setResponsibleAgencies(responsibleAgencies);
//                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                sgBlutdruckRecord.setResponsibleAgencies(responsibleAgencies);
            }
        } else {
            sysUser.setId(sysUser1.getId());
        }

        Map<String, Object> list = new HashMap<>();
        List<Map<String, Object>> threeHightSignNumber = sgSigningRecordService.threeHightSignNumber(sysUser.getOrgCode(), responsibleAgencies);
        threeHightSignNumber.forEach(item -> {
            if (Integer.parseInt(item.get("num1").toString()) != 0) {
                list.put("blutdruck", item.get("num1"));
            }
            if (Integer.parseInt(item.get("num2").toString()) != 0) {
                list.put("glucose", item.get("num2"));
            }
            if (Integer.parseInt(item.get("num3").toString()) != 0) {
                list.put("lipid", item.get("num3"));
            }
        });

        return Result.OK(list);
    }

    /**
     * TODO     five--今日新增居民,送药人数、送药数量
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/17 14:38
     * @Exception
     */
    @ApiOperation(value = "看板-five--今日新增居民,送药人数、送药数量", notes = "看板-five--今日新增居民,送药人数、送药数量")
    @GetMapping(value = "/fiveDataNumber")
    public Result<Map<String, Object>> fiveDataNumber() {
        // 获取当前登录用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String time = DateTime.now().toString("YYYY-MM-dd");
        Map<String, Object> list = new HashMap<>();
        // 获取当前登录用户的角色
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        // 获取当前机构名称
        String name = sysDepartService.getOne(new QueryWrapper<SysDepart>().eq("org_code", sysUser.getOrgCode())).getDepartName();

        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        List<String> responsibleAgencies = new ArrayList<>();
        QueryWrapper<SgSendMedicine> memberQueryWrapperBlutdruck = new QueryWrapper<>();
        if (roleCode.contains("dept_manage") || roleCode.contains("admin")) {
            // 机构管理员，查询的是本机构下的数据
            memberQueryWrapperBlutdruck.like("sys_org_code", sysUser.getOrgCode());
        }
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
                // queryWrapper.eq("doctor_id", sysUser1.getId().toString());
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
                // sgBlutdruckRecord.setResponsibleAgencies(responsibleAgencies);
                // queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
                // sgBlutdruckRecord.setResponsibleAgencies(responsibleAgencies);
            }
        } else {
            sysUser.setId(sysUser1.getId());
        }
        // 今日新增居民
        List<SgMember> sgMemberList = sgMemberService.getAddMemberByToday(sysUser.getOrgCode(), roleCode, sysUser.getId(), time, responsibleAgencies);
        list.put("dayMemberCount", sgMemberList.size());
        // 药品送药人数
        List<SgSendMedicine> sgSendMedicines = sgSendMedicineService.getRecordList(sysUser.getOrgCode(), roleCode, sysUser.getId(), responsibleAgencies);
        int song = '0';
        List<String> data = new ArrayList<>();
        for (SgSendMedicine item : sgSendMedicines) {
            if (!data.contains(item.getMemberId())) {
                data.add(item.getMemberId());
            }
            // 药品数量
            song += Integer.parseInt(item.getSendNum().toString());
        }
        // 送药人数
        list.put("peopleNumber", data.size());
        // 机构管理员可查询药品发放数量
        if (roleCode.contains("dept_manage")) {
            list.put("song", sgSendMedicineService.list(memberQueryWrapperBlutdruck).size());
        } else if (!roleCode.contains("admin") && !roleCode.contains("dept_manage")) {
            String list1 = sgSendMedicineService.queryBydoctorId(sysUser.getId());
            list.put("song", list1);
        }
        // 总建档人数
        List<SgMember> sgMemberSumList = sgMemberService.getAddMemberByToday(sysUser.getOrgCode(), roleCode, sysUser.getId(), null, responsibleAgencies);
        list.put("zong", sgMemberSumList.size());
        return Result.OK(list);
    }

    // endregion

    // region  小程序使用

    /**
     * TODO     今日血压/血糖/血脂预警人数
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/17 14:38
     * @Exception
     */
    @ApiOperation(value = "今日血压/血糖/血脂预警人数", notes = "今日血压/血糖/血脂预警人数")
    @GetMapping(value = "/bloodWarning")
    public Result<Map<String, Object>> bloodWarning() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        List<String> responsibleAgencies = new ArrayList<>();
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
//                queryWrapper.eq("doctor_id", sysUser1.getId().toString());
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                sgBlutdruckRecord.setResponsibleAgencies(responsibleAgencies);
//                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                sgBlutdruckRecord.setResponsibleAgencies(responsibleAgencies);
            }
        } else {
            sysUser.setId(sysUser1.getId());
        }
        String time = DateTime.now().toString("YYYY-MM-dd");
        Map<String, Object> list = new HashMap();
        // 获取当前登录用户的角色
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        // 血压
        List<SgBlutdruckRecord> sgBlutdruckRecordList = sgBlutdruckRecordService.dayMeasureNumberCount(sysUser.getOrgCode(), roleCode, time, sysUser.getId(), "0", responsibleAgencies);
//        血糖
        List<SgGlucoseRecord> sgGlucoseRecordList = sgGlucoseRecordService.dayMeasureNumberCount(sysUser.getOrgCode(), roleCode, time, sysUser.getId(), "0", responsibleAgencies);
//        血脂
        List<SgLipidRecord> sgLipidRecordList = sgLipidRecordService.dayMeasureNumberCount(sysUser.getOrgCode(), roleCode, time, sysUser.getId(), "0", responsibleAgencies);

        list.put("0", sgBlutdruckRecordList);
        list.put("1", sgGlucoseRecordList);
        list.put("2", sgLipidRecordList);
        return Result.OK(list);
    }

    /**
     * @description:
     * @author: xiaoHua 
     * @date: 2024/1/12 13:43
     * @param: []
     * @return: org.jeecg.common.api.vo.Result<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    @ApiOperation(value = "本年度高血压控制率总数", notes = "本年度高血压控制率总数")
    @GetMapping("/getYearControlRate")
    public Result<Double> getYearControlRate(Integer yearDate){
        // 查询本年度高血压总人数
        Integer yearSgCount = sgBlutdruckRecordService.getYearSgCount(yearDate);
        // 查询本年度未超出血压预警总人数
        Integer monthSgCount = sgBlutdruckRecordService.getMonthSgCount(yearDate);
        double ratio = (double) monthSgCount / yearSgCount * 100;
        DecimalFormat df = new DecimalFormat("#.##");
        double formattedRatio = Double.parseDouble(df.format(ratio));
        return Result.OK(formattedRatio);
    }

    /**
     * @description:
     * @author: xiaoHua 
     * @date: 2024/1/13 11:17
     * @param: [yearDate] 年份
     * @return: org.jeecg.common.api.vo.Result<java.util.Map<java.lang.String,java.lang.String>>
     **/
    @ApiOperation(value = "本年度高血压控制率", notes = "本年度高血压控制率")
    @GetMapping("/getMonthControlRate")
    public Result<Map<String, String>> calculateControlRate(Integer yearDate) {
        Map<String, String> controlRateMap = new HashMap<>();
        List<SgBlutdruckRecord> monthlist = sgBlutdruckRecordService.getMonthControlRate(yearDate);
        // 查询本月度未超出血压预警总人数
        List<SgBlutdruckRecord> monthlistXy = sgBlutdruckRecordService.getXyMonthControlRate(yearDate);

        // 遍历包含预警三高及体脂总人数的数据
        for (SgBlutdruckRecord monthData : monthlist) {
            String month = monthData.getMonth();
            int totalXy = Optional.ofNullable(monthData.getXyCount())
                    .map(Integer::parseInt)
                    .orElse(0);

            int totalXt = Optional.ofNullable(monthData.getXtCount())
                    .map(Integer::parseInt)
                    .orElse(0);

            int totalXz = Optional.ofNullable(monthData.getXzCount())
                    .map(Integer::parseInt)
                    .orElse(0);

            int totalTz = Optional.ofNullable(monthData.getTzCount())
                    .map(Integer::parseInt)
                    .orElse(0);

            // 遍历包含未超出预警三高及体脂总人数的数据
            for (SgBlutdruckRecord monthDataXy : monthlistXy) {
                if (monthDataXy.getMonth().equals(month)) {
                    String xyCountStr = monthDataXy.getXyCount();
                    int xyWithinLimit = (xyCountStr != null && !xyCountStr.isEmpty()) ? Integer.parseInt(xyCountStr) : 0;

                    String xtCountStr = monthDataXy.getXtCount();
                    int xtWithinLimit = (xtCountStr != null && !xtCountStr.isEmpty()) ? Integer.parseInt(xtCountStr) : 0;

                    String xzCountStr = monthDataXy.getXzCount();
                    int xzWithinLimit = (xzCountStr != null && !xzCountStr.isEmpty()) ? Integer.parseInt(xzCountStr) : 0;

                    String tzCountStr = monthDataXy.getTzCount();
                    int tzWithinLimit = (tzCountStr != null && !tzCountStr.isEmpty()) ? Integer.parseInt(tzCountStr) : 0;

                    // 计算控制率
                    double xyControlRate = (double) xyWithinLimit / totalXy * 100;
                    double xtControlRate = (double) xtWithinLimit / totalXt * 100;
                    double xzControlRate = (double) xzWithinLimit / totalXz * 100;
                    double tzControlRate = (double) tzWithinLimit / totalTz * 100;
                    // 如果结果不是有限的，则设置为0
                    xyControlRate = Double.isFinite(xyControlRate) ? xyControlRate : 0;
                    xtControlRate = Double.isFinite(xtControlRate) ? xtControlRate : 0;
                    xzControlRate = Double.isFinite(xzControlRate) ? xzControlRate : 0;
                    tzControlRate = Double.isFinite(tzControlRate) ? tzControlRate : 0;

                    // 将计算结果存入控制率Map
                    controlRateMap.putIfAbsent("month", "");
                    controlRateMap.putIfAbsent("xy", "");
                    controlRateMap.putIfAbsent("xt", "");
                    controlRateMap.putIfAbsent("xz", "");
                    controlRateMap.putIfAbsent("tz", "");

                    controlRateMap.put("month", controlRateMap.get("month") + "'" + month + "',");
                    controlRateMap.put("xy", controlRateMap.get("xy") + String.format("%.1f", xyControlRate) + ",");
                    controlRateMap.put("xt", controlRateMap.get("xt") + String.format("%.1f", xtControlRate) + ",");
                    controlRateMap.put("xz", controlRateMap.get("xz") + String.format("%.1f", xzControlRate) + ",");
                    controlRateMap.put("tz", controlRateMap.get("tz") + String.format("%.1f", tzControlRate) + ",");
                }
            }
        }
        // 移除末尾的逗号
        for (String key : controlRateMap.keySet()) {
            controlRateMap.put(key, controlRateMap.get(key).substring(0, controlRateMap.get(key).length() - 1));
        }
        return Result.OK(controlRateMap);
    }

    /**
     * 打印控制率Map
     *
     * @param controlRateMap 包含控制率的Map
     */
    private static void printControlRateMap(Map<String, String> controlRateMap) {
        for (String key : controlRateMap.keySet()) {
            System.out.println(key + ":" + controlRateMap.get(key));
        }
    }
}

    // endregion
